//
//  EditClipping.m
//  Bespoke
//
//  Created by Cheng on 12/8/23.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "EditClipping.h"
#import "MediaListsMedia.h"
#import "RequestAPIFunction.h"
#import "SelectBudgetCell.h"
#import "DetailMyBoardUIViewController.h"

#define CREATED_BOOK_ID -1
#define ModifyDetailMyBoard_API @"http://54.235.166.43/BeSpokeAPI/MyBoard/ModifyDetailMyBoard.php"

@implementation EditClipping
@synthesize TVw_Board, Bt_MediaCopy, Bt_SelectBoard, IVw_TableBoard, Lab_BookName;
@synthesize AMB_MyBoard,Check,Array_MediaSelected,Current_DetailMyBoard, BK_En_object, Array_List;
@synthesize delegate;

- (void)initArray:(NSMutableArray *)BoardArray {
    
    self.Array_List = [[NSMutableArray alloc] init];
    [self.Array_List addObjectsFromArray:BoardArray];
    [self.Array_List addObject:[[AccountBoard alloc] BoardID:CREATED_BOOK_ID name:@"New Book" ShareGroup:nil]];
    
    [self.TVw_Board reloadData];
}

- (IBAction)MediaCopyON:(id)sender
{
    [Bt_MediaCopy setImage:[UIImage imageNamed:@"radio_on.png"] forState:UIControlStateNormal];
    
    [Bt_MediaCopy removeTarget:self
                        action:@selector(MediaCopyON:)
              forControlEvents:(UIControlEvents)UIControlStateNormal];
    
    [Bt_MediaCopy addTarget:self
                     action:@selector(MediaCopyOff:)
           forControlEvents:UIControlEventTouchUpInside];
    
    Check = @"Copy";
}

- (void)MediaCopyOff:(id)sender
{
    [Bt_MediaCopy setImage:[UIImage imageNamed:@"radio_off.png"] forState:UIControlStateNormal];
    
    [Bt_MediaCopy removeTarget:self
                        action:@selector(MediaCopyOff:)
              forControlEvents:(UIControlEvents)UIControlStateNormal];
    
    [Bt_MediaCopy addTarget:self
                     action:@selector(MediaCopyON:)
           forControlEvents:UIControlEventTouchUpInside];
        
    Check = @"Move";
}

-(IBAction)editclippingsSelect:(id)sender
{
    TVw_Board.delegate = self;
    TVw_Board.dataSource = self;
    TVw_Board.hidden = false;
    IVw_TableBoard.hidden = false;
    [UIView animateWithDuration:0.5
                     animations:^{[TVw_Board setAlpha:1.0];[IVw_TableBoard setAlpha:1.0];}
                     completion:^(BOOL finished){ }];
}

-(IBAction)editclippingsDelete:(id)sender
{
    Check = @"Delete";
    
    [self ClippingAction];

}

-(IBAction)editclippingsDone:(id)sender {
    
    if ((Bt_SelectBoard.tag!=Current_DetailMyBoard.BoardID)&&(Bt_SelectBoard.tag!=0)) {
        
        [self ClippingAction];
    }
    else {
        UIAlertView *AlertView = [[UIAlertView alloc]initWithTitle:@"Alert" message:@"Please Select Correct Book." delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];
        [AlertView show];
    }
}

-(void)ClippingAction {
    
    NSMutableString* NS_MoveMediaXML = [NSMutableString string];
    NSMutableArray *Buffer_Array_MediaSelected = [[NSMutableArray alloc] initWithArray:Array_MediaSelected];
    NSMutableArray *Array_MediaSelectedIndex = [[NSMutableArray alloc] init];
    
    int MediaIndex = 0;
    
    //Select Media Pressed.
    for (id CurrentMedia in Array_MediaSelected) {
        
        if ([CurrentMedia isKindOfClass:[MediaListsMedia class]]) {
            
            [NS_MoveMediaXML appendString:[NSString stringWithFormat:@"<Media ID=\"%d\" />",((MediaListsMedia *)[Array_MediaSelected objectAtIndex:MediaIndex]).MediaID]];
            [Array_MediaSelectedIndex addObject:[NSString stringWithFormat:@"%d",MediaIndex]];
        }
        MediaIndex++;
    }
    
    //Clear unnecessary.
    [Array_MediaSelected removeObject:@"NonSelect"];
    
    for (AccountBoard *Board in AMB_MyBoard.BoardArray) {
        
        //Delete Media Request API.
        if ((Board.BoardID==Current_DetailMyBoard.BoardID)&&(![Check isEqualToString:@"Copy"])) {
            
            [self SendXMLtoAPI:Board SetXML:NS_MoveMediaXML SetAction:@"Delete"];
            
            //Replace select object in array.
            for (NSString *Index in Array_MediaSelectedIndex) {
                [Current_DetailMyBoard.MediaArray replaceObjectAtIndex:[Index intValue] withObject:@"Delete"];
                //[Board.MediaArray replaceObjectAtIndex:[Index intValue] withObject:@"Delete"];
            }
        
            //Delete object in array.
            [Current_DetailMyBoard.MediaArray removeObject:@"Delete"];
            //[Board.MediaArray removeObject:@"Delete"];
        }
        //Insert Media Request API.
        if ((Board.BoardID==self.Bt_SelectBoard.tag)&&(![Check isEqualToString:@"Delete"])) {
            
            [self SendXMLtoAPI:Board SetXML:NS_MoveMediaXML SetAction:@"Insert"];
            
            for (MediaListsMedia *CurrentCell in self.Array_MediaSelected)
                CurrentCell.x=CurrentCell.y=0;
            
            [Board.MediaArray addObjectsFromArray:self.Array_MediaSelected];
        }
    }
    
    [self.delegate DidSelected_EditClipping:Buffer_Array_MediaSelected SetAction:Check];
    
    [self.delegate uiViewTouched_EditClipping:NO];
}

#pragma mark - API Function

- (void)SendXMLtoAPI:(AccountBoard *)Board SetXML:(NSString *)NS_MoveMediaXML SetAction:(NSString *)Action  {
    
    NSData *responseData =
    [RequestAPIFunction XML_PostRequest:[NSString stringWithFormat:@"<AccountInfo UserName=\"%@\" Level=\"\" Name=\"%@\" Organization=\"\"><Board ID=\"%d\" Action=\"%@\">%@</Board></AccountInfo>",
                                         BK_En_object.userName,
                                         BK_En_object.fullName,
                                         Board.BoardID,
                                         Action,
                                         NS_MoveMediaXML]
                              urlString:ModifyDetailMyBoard_API];
    
    //No Network Connection or time out.
    if (responseData == nil)
        return;
}

#pragma mark - UITableViewDelegate


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    static NSString *ButtonCellIdentifier = @"SelectBudgetCell";
    SelectBudgetCell *TVwC_SelectCell = [tableView dequeueReusableCellWithIdentifier:ButtonCellIdentifier];
    
    UIView *bgColorView = [[UIView alloc] init];
    UIColor *UC_skyblue= [UIColor colorWithRed:206.0/255.0 green:235.0/255.0 blue:236.0/255.0 alpha:1.0];
    [bgColorView setBackgroundColor:UC_skyblue];
    
    if (TVwC_SelectCell == nil) {
        
        NSArray *Array_nib = [[NSBundle mainBundle] loadNibNamed:@"SelectBudgetCell" owner:nil options:nil];
        
        TVwC_SelectCell = [Array_nib objectAtIndex:0];
        
        [TVwC_SelectCell setSelectedBackgroundView:bgColorView];
    }
    
    AccountBoard *Board = [self.Array_List objectAtIndex:indexPath.row];
    TVwC_SelectCell.Lab_Price.text = Board.name;
    
    if ([TVwC_SelectCell.Lab_Price.text isEqualToString:@"New Book"]) {
        TVwC_SelectCell.IVw_Symbol.hidden = NO;
        TVwC_SelectCell.Lab_Price.frame = CGRectMake(TVwC_SelectCell.IVw_Symbol.frame.origin.x+TVwC_SelectCell.IVw_Symbol.frame.size.width,
                                                     TVwC_SelectCell.frame.origin.y,
                                                     TVwC_SelectCell.frame.size.width,
                                                     TVwC_SelectCell.frame.size.height);
    }
    
    return TVwC_SelectCell;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;  
}  

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section  
{
    return [self.Array_List count];  
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    AccountBoard *AB_Cell = [self.Array_List objectAtIndex:indexPath.row];
    [UIView animateWithDuration:0.2
                     animations:^{[TVw_Board setAlpha:0]; [IVw_TableBoard setAlpha:0];}
                     completion:^(BOOL finished){ }];
    
    if (AB_Cell.BoardID==CREATED_BOOK_ID)
        [self.delegate CreatedNewBookPressed];
    else {
        
        Lab_BookName.text = AB_Cell.name;
        Bt_SelectBoard.tag = AB_Cell.BoardID;
    }
}


#pragma mark - Touches
- (BOOL)pointInside:(CGPoint)point withEvent:(UIEvent *)event
{
    if( point.x > 0 && point.x < self.frame.size.width && point.y > 0 && point.y < self.frame.size.height )
    {
        [delegate uiViewTouched_EditClipping:YES ];
        return YES;
    }
    
    [delegate uiViewTouched_EditClipping:NO ];
    return NO;
}

@end
